<?php
namespace application\datatypes;
use application\datatypes\DataType;
use application\utilities\Utility;

class Code extends DataType {
	public static $name = 'Code';
	public static $fields = array(array('columnType'=>'LONGTEXT'));
	
	public static function formJS($field) {
		Modulator()->includeScript('jquery');
		Modulator()->includeScript(getCommonFile('third-party/jquery-linedtextarea/jquery-linedtextarea.js'));
		?><link rel="stylesheet" type="text/css" media="all" href="<?= getCommonFile('third-party/jquery-linedtextarea/jquery-linedtextarea.css') ?>" />
		<script type="text/javascript">
			$(document).ready(function() {
				$('#<?=$field->cf_column?>').linedtextarea();
				$('#<?=$field->cf_column?>').keydown(function(event) {
					if(event.keyCode == '9') {
						event.preventDefault();
						
					}
					
				});
			});
		</script>
		<?php
		
	}
	
	public static function validate($field, $data, $results) {
		if($field->cf_required && !$data[$field->cf_column]) {
			$results['errors'][] = '<b>'.$field->cf_display_name.'</b> is required.';
		}
		elseif($value = $data[$field->cf_column]) {
			$results['db_fields'][$field->cf_column] = htmlentities($value);	
		}
		
		return $results;
	}
	
	public static function display($formElements) {
		?>
		
		<fieldset class="single-field">
			<header><?=$formElements['display']?></header>
			<section class="inner">
			<?php if($description = $formElements['description']) : ?>
				<p class="form-description"><?=$description?></p>
			<?php endif;?>
			<?=$formElements['elements']['element']?>
			</section>
		</fieldset>
		<?php
	}
	
	public static function build($field, $data) {
		$value = html_entity_decode($data[$field->cf_column]);
		$formElements = array('description'=>$field->cf_description, 'column'=>$field->cf_column, 'display'=>$field->cf_display_name, 'data_type'=>$field->cf_data_type, 'elements'=>array(
						'element'=>
							sprintf('<textarea class="code" name="%1$s" id="%1$s">%2$s</textarea>', $field->cf_column, $value)
						
		));
		return $formElements;
	
	}
	
	public static function prepareData($field, $data, $params) {
		return '<pre><code>'.$data[$field->cf_column].'</code></pre>';
	}
		
}
?>